import { InjectRedis } from '@nestjs-modules/ioredis';
import { Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import { RecommendationService } from '../recommendation/recommendation.service';

@Injectable()
export class LikeService {
  constructor(
    @InjectRedis() private readonly redis: Redis,
    private readonly recommendationService: RecommendationService,
  ) {}

  /**
   * @description 点赞/取消点赞
   */
  async toggleLike(userId: string, videoId: string): Promise<boolean> {
    const keyUserLikes = `user_likes:${userId}`;
    const keyVideoLikes = 'video_likes';
    const keySyncQueue = 'sync_queue';

    // 检查是否已点赞
    const isLiked = await this.redis.sismember(keyUserLikes, videoId);

    // 使用Redis事务保证原子性
    const pipeline = this.redis.multi();

    if (isLiked) {
      // 取消点赞
      pipeline.hincrby(keyVideoLikes, videoId, -1).srem(keyUserLikes, videoId);
    } else {
      // 点赞
      pipeline.hincrby(keyVideoLikes, videoId, 1).sadd(keyUserLikes, videoId);
    }

    // 记录到同步队列
    pipeline.sadd(keySyncQueue, videoId);

    await pipeline.exec();

    // 操作完成后，更新用户的推荐缓存
    await this.recommendationService.invalidateRecommendationCache(
      Number(userId),
    );
    return !isLiked;
  }

  /**
   * @description 判断当前用户对视频是否点赞
   */
  async isLiked(userId: string, videoId: string): Promise<boolean> {
    const keyUserLikes = `user_likes:${userId}`;
    const isLiked = this.redis.sismember(keyUserLikes, videoId);
    return !!isLiked;
  }
}
